<template>
  <div class="app-container">
   <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
      <el-form-item label="提箱单号">
        <el-input v-model.trim="param.packingNo" clearable placeholder="请输入提箱单号"></el-input>
      </el-form-item>
      <el-form-item label="箱型">
        <el-select v-model="param.boxType" clearable style="width:100%" placeholder="选择箱型">
          <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="箱况">
        <el-select v-model="param.boxCondition" clearable style="width:100%" placeholder="选择箱况">
          <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model.trim="param.buyBoxCompanyName" clearable placeholder="请输入客户"></el-input>
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model.trim="param.orderNo" clearable  placeholder="请输入订单号"></el-input>
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReset">重置</el-button>
      </div>   
    </div>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button size="small" @click="exportSaleBoxPacking" plain>导出 </el-button>
      <el-button size="small" @click="endPacking" plain>提完 </el-button>
      <el-button size="small" @click="handlePacking" type="primary" plain>开出售提箱单</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" style="width: 100%;" @downloadFile="downloadFile" @pageChange="onTablePageChange" @showInfo="showInfo" @activeAddPacking="activeAddPacking" @showPackingRecord="showPackingRecord" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 开提箱单 -->
    <el-drawer v-model="param.drawerPacking" :show-close="false" :with-header="false" size="40%">
      <div :key="Date.now()">
        <buildPacking :packingInfo="param.packingInfo"  :drawerConfig="drawerConfig" :isPitch=true @successPacking="successPacking"></buildPacking>
      </div>
    </el-drawer>

    <!-- 添加提箱记录 -->
    <el-drawer v-model="param.drawerPackingDetail" :with-header="false" size="40%">
      <span class="_before">添加提箱记录</span>
      <el-form ref="ruleRef" :model="param" :rules="rules" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="提箱单号">{{ rowData.packingNo }}</el-form-item>
        <el-form-item label="选择订单" prop="yardName">
          <el-table ref="orderListref" :data="param.orderList" @selection-change="handleSelectionChange" style="width: 100%">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="订单号" prop="orderNo" width="200" align="center"/>
              <el-table-column label="下单日期" prop="orderTime" width="120" align="center">
                <template #default="scope">{{formatDate(scope.row.orderTime,2)}}</template>
              </el-table-column>
              <el-table-column label="已提箱量" prop="packedQuantity" align="center"/>
              <el-table-column label="未提箱量" align="center">
                <template #default="scope">{{ scope.row.totalQuantity - scope.row.packedQuantity }}</template>
              </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="堆场名称" prop="yardName"><el-input v-model="param.yardName" maxlength="50"></el-input> </el-form-item>
        <el-form-item label="箱型">{{ boxTypeFilter(rowData.boxType) }} </el-form-item>
        <el-form-item label="箱况">{{ boxConditionFilter(rowData.boxCondition) }}</el-form-item>
        <!-- <el-form-item label="司机信息" prop="driverInfo">
          <el-input v-model.trim="param.driverInfo" :maxlength="100" show-word-limit></el-input>
        </el-form-item> -->
       
        <el-form-item v-if="param.isChangeBox == '10'" label="箱号" prop="containerNo">
          <el-select v-if="hasContainerNos" v-model="param.containerNo">
            <el-option v-for="item in param.containerNos" :key="item.containerNo" :label="item.containerNo"
              :value="item.containerNo"></el-option>
          </el-select>
          <el-input v-else v-model.trim="param.containerNo"></el-input>
        </el-form-item>
        <template v-else>
          <el-form-item label="原箱号" prop="oidContainerNo">
            <el-select v-if="hasContainerNos" v-model="param.oidContainerNo">
              <el-option v-for="item in param.containerNos" :key="item.containerNo" :label="item.containerNo"
                :value="item.containerNo"></el-option>
            </el-select>
            <el-input v-else v-model="param.containerNo"></el-input>
          </el-form-item>
          <el-form-item label="实提箱号" prop="containerNo">
            <el-input v-model="param.containerNo"></el-input>
          </el-form-item>
        </template>
       
        <el-form-item label="换箱" v-if="param.containerNos.length > 0">
          <el-radio-group v-model="param.isChangeBox" @change="handleChangeNo"> 
            <el-radio value="5" size="large">是</el-radio>
            <el-radio value="10" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提箱日期" prop="packingDate">
          <el-date-picker v-model="param.packingDate" type="date" :editable="false" :clearable="false" placeholder="选择日期" :default-value="new Date()" />
        </el-form-item>
        <el-form-item label="提箱附件" prop="packingFileUrls">
          <!-- <img-upload ref="packingRef" :type="'pdf_jpg_png_zip'" :multiple="true" :exceed="false" :limit="'10'" v-model="param.packingFileUrls" /> -->
          <ImgUpload ref="packingRef" :type="'jpg/png/jpeg/pdf/zip'" :showNumber="4" :displayType="3" :limit="10" :drag="true"></ImgUpload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddPackingDetail">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 提箱记录 -->
    <el-drawer v-model="param.drawer3" :with-header="false">
      <span class="_before">提箱记录</span>
      <div style="float: right;margin-top: 60px;">
        <span>应提箱量：{{ rowData.totalQuantity || "0" }} 个</span> &nbsp;
        <span>实提箱量：{{ rowData.packedQuantity || "0" }} 个</span>
      </div>
      <el-table :data="packingRecord" style="margin-top: 100px;">
        <el-table-column prop="containerNo" label="箱号" />
        <el-table-column prop="boxType" label="箱型" />
        <el-table-column prop="boxCondition" label="箱况" />
        <el-table-column label="提箱日期">
          <template #default="scope">
            {{ formatDate(scope.row.packingDate, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="buyBoxCompanyName" label="客户" />
      </el-table>
    </el-drawer>

    <!-- info -->
    <el-dialog v-model="param.dialogVisibleInfo" :with-header="false" width="650">
      <span class="_before">提箱单详情</span>
      <el-row justify="center" align="middle" class="marginTop10 elRow-box" >
        <el-col :offset="2" :span="18" class="marginTop10"><span>客户:</span><span>{{ param.boxInfo.buyBoxCompanyName }}</span></el-col>
        <el-col :offset="2" :span="18" class="marginTop10"><span>提箱单号:</span><span>{{ param.boxInfo.packingNo }}</span></el-col>
        <el-col :offset="2" :span="18" class="marginTop10"><span>售箱订单:</span>
          <div class="marginTop10">
            <el-table :data="param.boxInfo.tableOrder">
                <el-table-column prop="orderNo" label="订单号" width="200"> </el-table-column>
                <el-table-column prop="planPickupDate" label="预计提箱日期" width="150">
                  <template #default="scope">
                    {{ formatDate(scope.row.planPickupDate, 2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="下单日期">
                  <template #default="scope">
                    {{ formatDate(scope.row.createTime, 2) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
        </el-col>
        <el-col :offset="2" :span="18" class="marginTop10"><span>箱型/箱况/箱量:</span>
          <div class="marginTop10">
            <el-table :data="param.boxInfo.tableBox">
              <el-table-column prop="boxType" label="箱型"> </el-table-column>
              <el-table-column prop="boxCondition" label="箱况"> </el-table-column>
              <el-table-column prop="totalQuantity" label="箱量"> </el-table-column>
           </el-table>
          </div>
        </el-col>
         <el-col :offset="2" :span="18" class="marginTop10"><span>提箱单附件:</span>
          <span><showFile :detailFileList="param.boxInfo.packingFileList"></showFile></span>
        </el-col>
         <el-col :offset="2" :span="18" class="marginTop10"><span>状态:</span><span>{{ param.statusFilter[param.boxInfo.status] }}</span></el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { getContainerNosByPackingId, exportSaleBoxPackingList,orderBoxQty, saleBoxPage, batchFinish, getPackingInfo } from '@/api/boxDeal/tiXiangManage'
import { formatDate } from '@/utils'
import { downloadIamge,downloadFile } from '@/utils/download'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { addPackingDetail, saleBoxPage as getDetailTable } from '@/api/boxDeal/tiXiangManageDetail';
import buildPacking from '@/views/components/packingBuild.vue';
import showFile from '@/components/upload/showFile'
import { computed, getCurrentInstance, onMounted, onActivated, reactive, ref } from 'vue';
// import imgUpload from '@/components/upload/index'
import ImgUpload from '@/components/upload/uploadFiles-Images'
import {Plus,Delete,Edit,Message,Search,Download,Upload,Refresh,UploadFilled} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {useRoute} from 'vue-router'

const param = reactive({
  value1: [],
  boxInfo: { code: '123456789', type: "40HQ", info: "无", tableBox:[], tableOrder:[] },
  pageNum: 0,
  pageSize: 10,
  dialogTableVisible: false,
  drawer: false,
  dialogEditVisible: false,
  dialogVisible: false,
  dialogPathVisible: false,
  statusFilter: { 5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成' },
  packingDate: new Date(),
  isChangeBox: '10',
  packingNo:'',
  orderNo:'',
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    //{ value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  containerNos:[],
  drawerPacking:false,
  orderList:[]
});
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'packingNo', colWidth: '180', title: '提箱单号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'orderList', key2: 'orderNo', colWidth: '200', title: '订单号', type: '/', isCheck: true },
    { key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '80', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'residuePackingDays', colWidth: '150', title: '剩余提箱天数', isTooltip: true, tooltip: "负数代表超期未提天数", type: 'days',  after: '天',isCheck: true },
    { key: 'totalQuantity', colWidth: '80', title: '总箱量', type: 'totalQuantity', isCheck: true },
    { key: 'packedQuantity', colWidth: '80', title: '已提箱量', type: 'totalQuantity', isCheck: true },
    { key: 'totalQuantity',key2: 'packedQuantity', colWidth: '80', title: '未提箱量', type: 'quantity', isCheck: true },
    { key: 'status', colWidth: '70', title: '状态', type: 'statusTixiang',  isCheck: true },
    { key: 'packingValidityPeriodStart',key2: 'packingValidityPeriodEnd', colWidth: '200', title: '提箱单有效期范围', type: 'rangeStatus2', isCheck: true },
    { key: 'buyBoxCompanyName',colWidth: '250', title: '客户', type: 'text', isCheck: true },
    { key: 'agentUserName', colWidth: '70', title: '联系人', type: 'text', isCheck: true },
    { key: 'agentUserTel',colWidth: '140', title: '联系电话', type: 'phoneNumber',areaCode:"agentUserAreaCode", isCheck: true },
    {
      key: 'operate',
      colWidth: '180',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // icon: 'ChatLineSquare',
          command: 'showPackingRecord', //param.drawer3
          // content: '提箱记录',
          name: '提箱记录',

        },
        {
          // icon: 'Download',
          command: 'downloadFile',
          // content: '下载提箱单',
          name: '下载',
        },
        {
          // icon: 'Plus',
          command: 'activeAddPacking', // addPacking
          // content: '添加记录',
          name: '添加记录',
          isShow: (row: any) => {
            return row.status <= 15;
          },
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

const typeList = computed(() => {
  const list = [{ id: 0, name: '全部' }, { id: 5, name: '已发放' }, { id: 10, name: '已下载' }, { id: 15, name: '提箱中' }, { id: 20, name: '已完成' }]
  return list
})

const rules = ref({
  yardName: [{ required: true, message: "不能为空", trigger: "blur" }],
  driverInfo: [
    { required: true, message: "不能为空", trigger: "blur" },
    { pattern: /^[^\uD800-\uDBFF\uDC00-\uDFFF\uD83C\uDDE6-\uDDFF\u2000-\u206F]+$/, message: '不允许输入表情符号', trigger: 'blur' }
  ],
  containerNo: [
    { required: true, message: "不能为空", trigger: "blur" },
    { pattern: /^[A-Z]{3}U\d{7}$/, message: "箱号格式为4个大写字母+7个数字", trigger: "blur" }
  ],
  oidContainerNo: [{ required: true, message: "不能为空", trigger: "blur" }],
  packingDate: [{ required: true, message: "不能为空", trigger: "blur" }],
  packingFileUrls: [{ required: false, message: "不能为空", trigger: "blur" }],
  orderList: [{ required: true, message: "不能为空", trigger: "blur" }],
  // email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
  // phonenumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
});
const route = useRoute();

onActivated(() => {
  if(route.query.refNo){
    param.packingNo=route.query.refNo
  }
  getTableData()
})

/*
# 卖箱公司: 查询提箱单分页列表
# 过滤条件： 提箱单号:String packingNo   箱况:boxCondition   箱型:boxType
# 提箱单状态 5-已发放 10-已下载 15-提箱中 20-已完成  Integer status
# 买箱公司Id:buyBoxCompanyId  买箱公司名称:buyBoxCompanyName 
*/
const getTableData = () => {
  const data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    packingNo: param.packingNo?.toUpperCase(),
    boxType: param.boxType,
    boxCondition: param.boxCondition,
    buyBoxCompanyName: param.buyBoxCompanyName,
    orderNo: param.orderNo?.toUpperCase(),
    status: param.status,
  }
  saleBoxPage(data).then((res: any) => {
    table.data = res.data.list;
    table.config.total = res.data.total;
    // drawerConfig.boxCondition = res.data.boxCondition;
    // drawerConfig.boxType = res.data.boxType;
  })
}

//重置
function handleReset() {
  param.packingNo = null
  param.boxType = null
  param.boxCondition = null
  param.buyBoxCompanyName = null
  param.orderNo = null
  getTableData()
}

function handleTypeChange(val: any) {
  // console.log(val)
  param.status = val
  getTableData()
}

// 去开提箱单
const drawerConfig = reactive({
  citingSources: "",
  type: 1,  // 0：订单内开提箱单 1:提箱单管理内开提箱
  boxType: 0,
  boxCondition: 0
})

//开提箱单-售箱
const handlePacking = () => {
  param.drawerPacking = true
  param.packingInfo = { orderType: 200 }
};
const successPacking = () => {
  getTableData()
  ElMessage.success('提箱单开具成功！')
  param.drawerPacking = false
}

//下载--------------- 
const downloadFile = (rowData: any) => {
  // if(rowData.status == "20") return ElMessage.warning('已下载过提箱单,请勿重复下载')
  if (rowData.packingFileList) {
    const pdfFile = JSON.parse(rowData.packingFileList)
    if (pdfFile.length < 1 || !pdfFile[0].url) return ElMessage.error('chengzhi 未找到文件')
    downloadIamge(pdfFile[0].url)
  } else {
    ElMessage.error('chengzhi 未找到文件')
  }
}
const infoDownloadFile = (file: any) => {
  if (file) {
    if (!file.url) return ElMessage.error('chengzhi 未找到文件')
    downloadIamge(file.url)
  } else {
    console.log(rowData)
    ElMessage.error('chengzhi 未找到文件')
  }
}

//提箱记录

// 提箱单 有箱号
const hasContainerNos = computed(() => {
  if (param.containerNos && param.containerNos.length > 0) {
    return true
  } else {
    return false
  }
})

// 添加提箱记录弹窗
const { proxy } = getCurrentInstance();
const rowData = ref({})
const packingRef = ref()
const activeAddPacking = (row: any) => {
  rowData.value = row
  getContainerNosByPackingId(row.id).then((res: any) => {
    param.containerNos = res.data
    param.driverInfo = null
    param.yardName = null
    param.containerNo = null
    param.isChangeBox = '10'
  })
  orderBoxQty(rowData.value.id).then((res: any) => { 
    if(res.code == '00000'){
      param.orderList = res.data || []
    }
  })
  param.packingDate = new Date()
  packingRef.value?.clearFiles()
  param.drawerPackingDetail = true
}

// 添加提箱记录

const selectedItems = ref<any[]>([])
const orderListref = ref()
const handleSelectionChange = (selection: any[]) =>{
    selectedItems.value = selection
    if (selection.length > 1) {
      // 如果选择了多行，只保留最后一行
      orderListref.value?.clearSelection();
      orderListref.value?.toggleRowSelection(selection[selection.length - 1]);
    }
}
const handleAddPackingDetail = async () => {
  proxy.$refs.ruleRef.validate(valid => {
    if (valid) {
      // const imgList = packingRef.value.resultList || []
      const imgList = packingRef.value.fileList || []
      if(selectedItems.value.length < 1) return ElMessage.error('请选择订单')
      const data = {
        "packingId": rowData.value.id,
        "containerNo": param.containerNo,
        // "driverInfo": param.driverInfo,
        "packingDate": param.packingDate,
        "yardName": param.yardName,
        "detailFileList": JSON.stringify(imgList) || null,
        "isChangeBox": param.isChangeBox, //是否换箱 5-是  10-否 
        "oidContainerNo": param.isChangeBox == '5' ? param.oidContainerNo : null,
        "orderId": selectedItems.value[0].orderId || ''
      }
      if (param.isChangeBox) {
        data.oidContainerNo = param.oidContainerNo
      }
      addPackingDetail(data).then((res: any) => {
        getTableData()
        param.drawerPackingDetail = false
      })
    } else {
      return false
    }
  })
}

const handleChangeNo = (val) => {
  if(val == 5){
    param.oidContainerNo = param.containerNo
    param.containerNo = ''
  }
}

//查看提箱记录
const packingRecord = ref([])
const showPackingRecord = (row: any) => {
  param.drawer3 = true
  rowData.value = row
  const data = {
    pageNum: 1,
    pageSize: 200,
    packingId: row.id
  }
  getDetailTable(data).then((res: any) => {
    let list = res.data.list
    list.forEach((item: any) => {
      item.boxCondition = boxConditionFilter(item.boxCondition)
      item.boxType = boxTypeFilter(item.boxType)
    })
    packingRecord.value = list
  })
}

//提完
const tableRef = ref({ multipleSelection: [] })
const endPacking = (row: any) => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const selection = checkAllItem
  if (selection.length == 0) {
    return ElMessage.warning('请选择操作行')
  }
  let packingNosStr = getPackingNosStr(selection, 'packingNosStr')
  let idList = getPackingNosStr(selection, 'idList')
  ElMessageBox.confirm('确定提箱单 ' + packingNosStr + ' 已提完吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    batchFinish(idList).then((res: any) => {
      getTableData()
      ElMessage.success(packingNosStr + '已提完')
    })
  }).catch(() => { });
}

const getPackingNosStr = (selection: any, need: string) => {
  let str = ''
  let list: any = []
  selection.forEach((item: any, index: number) => {
    let dos = index ? ' , ' : ''
    str += dos + item.packingNo
    list.push(item.id)
  })
  if (need == 'packingNosStr') {
    return str
  }
  if (need == 'idList') {
    return list
  }
}

//详情
const showInfo = (row: any) => {
  if (!row.id) {
    ElMessage.error('提箱单 id 为空')
  }
  getPackingInfo(row.id).then((res: any) => {
    let resp = res.data
    param.boxInfo = resp
    const orderList = JSON.parse(resp.orderList)
    param.boxInfo.tableOrder = orderList
    let boxObj = { 
      boxType: boxTypeFilter(resp.boxType),
      totalQuantity: resp.totalQuantity,
      boxCondition: boxConditionFilter(resp.boxCondition)
    }
    param.boxInfo.tableBox = [boxObj]
    param.boxInfo.packingFileList = resp.packingFileList
    // param.boxInfo.packingFileList.push(param.boxInfo.packingFileList[0])
  })
  param.dialogVisibleInfo = true;
};

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

const selectids = computed(() => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  let ids: any[] = []
  checkAllItem.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
// 导出提箱单
const exportSaleBoxPacking = ()=>{
  if (selectids.value.length == 0) {
    return ElMessage.warning('请选择操作行')
  }
  ElMessageBox.confirm('确定要到导出提箱单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportSaleBoxPackingList({"packingListIds":selectids.value}).then((res: any) => {
        downloadFile(res, '提箱单详情')
    })
   
  }).catch(() => { });
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await saleBoxPage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

</script>

<style lang="scss" scoped>
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
.elRow-box{
  font-size: 16px;
  span{
    margin-right: 5px;
  }
  span:first-child{
    font-weight: 500;
  }
}
</style>
